$(document).ready(function() {
	update();
	setInterval(function(){ 
		update();
	}, 10000);
	$("#createGame").click(function(){
		$.ajax({
			type: "POST",
			url: 'game',
			data : {comand: "create"}		  		
		}).done(function(data){
			window.location = 'index.html';
		});
	});


	FB.getLoginStatus(function(response) {
		if (response.status === 'connected') {
			FB.api('/me', function(response) {
				var username=response.name;
				$.ajax({
					type: "POST",
					url: "login",
					data: {username : username},
					success: function(){
						$('form#submit').hide(function(){$('div.success').fadeIn();});
						$('#createGame').css({"display":"center"}).fadeIn();

					}
				});

				document.getElementById('DivLogin').innerHTML = "";
				document.getElementById('nick').innerHTML = "Welcome, "+response.name+"! <a href='' onclick='FB.logout();'>Logout?</a>";
			});	


		}
	});

});

function facebook_onlogin (origin) {
	document.location.href = "lobby.html";
}

function update() {
	$.ajax({
		type:"GET",
		url:"game",
		dataType:"html",
		success:function(data)
		{
			$("#gameTab").html(data);
			$(".join").click(function(){
				$.ajax({
					type: "POST",
					url: 'game',
					data : {comand: $(this).attr("id")},
					success: function(data) {
						if(data==="error"){
							alert("This game is already going, try to join another.");
							document.location.href = "lobby.html";
						}
					}
				}).done(function(data){
					window.location = 'index.html';
				});
			});
			$(".info").click(function(){
				$.ajax({
					type: "GET",
					url: 'stats',
					data : {user: $(this).attr('id')},
					dataType: "html",
				}).done(function(data){

					$("#content").prepend(data);
					$('#dialog').dialog({
						autoOpen: true

					});
				});
			});
		}
	});
}

